package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.util.MD5;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.base.util.RandomValue;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.mapper.UserLoginRecordMapper;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.entity.UserLoginRecord;
import com.atguigu.srb.core.pojo.query.UserInfoQuery;
import com.atguigu.srb.core.pojo.vo.LoginVO;
import com.atguigu.srb.core.pojo.vo.RegisterVO;
import com.atguigu.srb.core.pojo.vo.UserIndexVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.impl.AMQImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Random;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author TieZhu
 * @since 2021-06-10
 */
@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserAccountMapper userAccountMapper;
    @Resource
    private UserLoginRecordMapper userLoginRecordMapper;


    @Transactional( rollbackFor = {Exception.class})
    @Override
    public void register(RegisterVO registerVO) {
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",registerVO.getMobile());
        Integer count=baseMapper.selectCount(queryWrapper);
        Assert.isTrue(count==0, ResponseEnum.MOBILE_EXIST_ERROR);
        //插入用户基本信息
        UserInfo userInfo=new UserInfo();
        userInfo.setUserType(registerVO.getUserType());
        log.info("用户手机号码："+registerVO.getMobile());
        userInfo.setMobile(registerVO.getMobile());
        userInfo.setNickName(registerVO.getNickName());
        userInfo.setName(registerVO.getNickName());
        userInfo.setPassword(MD5.encrypt(registerVO.getPassword()));
        userInfo.setStatus(UserInfo.STATUS_NORMAL);
        userInfo.setHeadImg("https://srb-file-lmz.oss-cn-beijing.aliyuncs.com/avatar/01.jpg");
        baseMapper.insert(userInfo);
        //创建会员账户
        UserAccount userAccount=new UserAccount();
        userAccount.setUserId(userInfo.getId());
        userAccountMapper.insert(userAccount);

    }


    @Override
    public UserInfoVO login(LoginVO loginVO, String ip) {
        String mobile=loginVO.getMobile();
        String pwd=loginVO.getPassword();
        Integer userType=loginVO.getUserType();
        //获取会员
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        queryWrapper.eq("user_type",userType);
        UserInfo userInfo=baseMapper.selectOne(queryWrapper);

        //用户不存在
        Assert.notNull(userInfo,ResponseEnum.LOGIN_MOBILE_ERROR);
        //校验密码
        Assert.equals(MD5.encrypt(pwd),userInfo.getPassword(),ResponseEnum.LOGIN_PASSWORD_ERROR);
        //查看用户是否被禁
        Assert.equals(userInfo.getStatus(),UserInfo.STATUS_NORMAL,ResponseEnum.LOGIN_LOKED_ERROR);
        //记录登录日志
        UserLoginRecord userLoginRecord=new UserLoginRecord();
        userLoginRecord.setIp(ip);
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecordMapper.insert(userLoginRecord);

        //生成token
        String token= JwtUtils.createToken(userInfo.getId(),userInfo.getName());
        System.out.println("service层"+token);
        UserInfoVO infoVO=new UserInfoVO();
        infoVO.setToken(token);
        infoVO.setMobile(userInfo.getMobile());
        infoVO.setName(userInfo.getName());
        infoVO.setNickName(userInfo.getNickName());
        infoVO.setHeadImg(userInfo.getHeadImg());
        infoVO.setUserType(userInfo.getUserType());
        return infoVO;
    }

    @Override
    public int resetPwd(RegisterVO registerVO) {
        String mobile=registerVO.getMobile();
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        userInfo.setPassword(MD5.encrypt(registerVO.getPassword()));
        int i = baseMapper.updateById(userInfo);
        return i;
    }

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> pageParam, UserInfoQuery userInfoQuery) {
        String mobile=userInfoQuery.getMobile();
        Integer status=userInfoQuery.getStatus();
        Integer userType=userInfoQuery.getUserType();

        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        if(userInfoQuery == null){
            return baseMapper.selectPage(pageParam, null);
        }
        queryWrapper
                .eq(StringUtils.isNotBlank(mobile), "mobile", mobile)
                .eq(status != null, "status", userInfoQuery.getStatus())
                .eq(userType != null, "user_type", userType);
        return baseMapper.selectPage(pageParam,queryWrapper);
    }
    @Override
    public void insertDate(){
        UserInfo userInfo = new UserInfo();
        for (int i = 0; i < 100; i++) {

            userInfo.setNickName(RandomValue.getChineseName());
            userInfo.setName(RandomValue.getChineseName());
            userInfo.setPassword(MD5.encrypt("123456"));
            userInfo.setMobile(RandomValue.getTel());
            userInfo.setUserType(1);
            userInfo.setHeadImg("https://srb-file-lmz.oss-cn-beijing.aliyuncs.com/avatar/01.jpg");
            userInfo.setStatus(UserInfo.STATUS_NORMAL);
            userInfo.setIntegral(new Random().nextInt(20000));
            baseMapper.insert(userInfo);
        }
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    @Override
    public boolean checkMobile(String mobile) {
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(mobile),"mobile",mobile);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count>0;
    }

    @Override
    public UserIndexVO getIndexUserInfo(Long userId) {
        //用户信息
        log.info("userId"+userId);
        UserInfo userInfo = baseMapper.selectById(userId);

        //账户信息
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_id", userId);
        UserAccount userAccount = userAccountMapper.selectOne(userAccountQueryWrapper);

        //登录信息
        QueryWrapper<UserLoginRecord> userLoginRecordQueryWrapper = new QueryWrapper<>();
        userLoginRecordQueryWrapper
                .eq("user_id", userId)
                .orderByDesc("id")
                .last("limit 1");
        UserLoginRecord userLoginRecord = userLoginRecordMapper.selectOne(userLoginRecordQueryWrapper);

        //组装结果数据
        UserIndexVO userIndexVO = new UserIndexVO();
        userAccount.setUserId(userInfo.getId());
        userIndexVO.setUserType(userInfo.getUserType());
        userIndexVO.setName(userInfo.getName());
        userIndexVO.setNickName(userInfo.getNickName());
        userIndexVO.setHeadImg(userInfo.getHeadImg());
        userIndexVO.setBindStatus(userInfo.getBindStatus());
        userIndexVO.setAmount(userAccount.getAmount());
        userIndexVO.setFreezeAmount(userAccount.getFreezeAmount());
        log.info(userLoginRecord.getCreateTime().toString());
        userIndexVO.setLastLoginTime(userLoginRecord.getCreateTime());
        System.out.println(userIndexVO.toString());
        return userIndexVO;
    }

    @Override
    public String getMobileByBindCode(String bindCode) {
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("bind_code",bindCode);
        UserInfo userInfo=baseMapper.selectOne(queryWrapper);
        return userInfo.getMobile();
    }
}
